package courseSystem.servlet;

import courseSystem.bean.CourseBean;
import courseSystem.bean.UserBean;
import courseSystem.data.DB;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CourseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        switch (req.getParameter("flag")) {
            case "add":
                addCourse(req, resp);
                break;
            case "delete":
                deleteCourse(req, resp);
                break;
            case "update":
                updateCourse(req, resp);
                break;
            case "all":
                allCourses(req, resp);
                break;
            case "my":
                myCourses(req, resp);
                break;
            case "find":
                findCourses(req, resp);
                break;
            case "choose":
                chooseCourse(req, resp);
                break;
            case "withdraw":
                withdrawCourse(req, resp);
                break;
            case "export":
                exportCourse(req, resp);
                break;
            default:
                req.getSession().setAttribute("prompt", "非法访问");
                req.getRequestDispatcher("index.jsp").forward(req, resp);
                break;
        }
    }

    private void addCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HashMap<String, String> m = new HashMap<>();
        m.put("course_id", (int) (Math.random() * 1000000) + "");
        setCourse(req, m);
        if (new DB().insert("course", m.keySet().toArray(new String[0]), m.values().toArray(new String[0])))
            req.getSession().setAttribute("prompt", "添加成功");
        else req.getSession().setAttribute("prompt", "添加失败");
        allCourses(req, resp);
    }

    private void deleteCourse(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        if (new DB().delete("course", "course_id='" + req.getParameter("course_id") + "'"))
            req.getSession().setAttribute("prompt", "删除成功");
        else req.getSession().setAttribute("prompt", "删除失败");
        if (req.getSession().getAttribute("keyWord") == null)
            allCourses(req, resp);
        else findCourses(req, resp);
    }

    private void updateCourse(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        HashMap<String, String> m = new HashMap<>();
        setCourse(req, m);
        if (new DB().update("course", m.keySet().toArray(new String[0]), m.values().toArray(new String[0]), "course_id='" + req.getParameter("course_id") + "'"))
            req.getSession().setAttribute("prompt", "修改成功");
        else req.getSession().setAttribute("prompt", "修改失败");
        if (req.getSession().getAttribute("keyWord") == null)
            allCourses(req, resp);
        else findCourses(req, resp);
    }

    private void chooseCourse(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        String course_id = req.getParameter("course_id");
        UserBean u = (UserBean) req.getSession().getAttribute("user");
        if (new DB().insert("student_course", new String[]{"student_id", "course_id"}, new String[]{u.getUser().get("id"), course_id}))
            req.getSession().setAttribute("prompt", "选课成功");
        else req.getSession().setAttribute("prompt", "选课失败");
        myCourses(req, resp);
    }

    private void withdrawCourse(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        String course_id = req.getParameter("course_id");
        UserBean u = (UserBean) req.getSession().getAttribute("user");
        if (new DB().delete("student_course", "student_id='" + u.getUser().get("id") + "' and course_id='" + course_id + "'"))
            req.getSession().setAttribute("prompt", "退课成功");
        else req.getSession().setAttribute("prompt", "退课失败");
        myCourses(req, resp);
    }
    private void exportCourse(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<CourseBean>myCourses=getMyCourses(req);
        StringBuilder s=new StringBuilder();
        for(String key:myCourses.get(0).getCourse().keySet())
            s.append(key).append("\t\t");
        for(CourseBean c:myCourses) {
            s.append("\n");
            for (String v:c.getCourse().values())
                s.append(v).append("\t\t");
        }
        req.getSession().setAttribute("export",s.toString());
        allCourses(req,resp);
    }

    private void allCourses(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<CourseBean> list = new ArrayList<>();
        for (HashMap<String, String> m : new DB().query("*", "course", ""))
            list.add(new CourseBean(m));
        req.getSession().setAttribute("courseClass", "allCourses");
        req.getSession().setAttribute("keyWord", null);
        req.getSession().setAttribute("findCourses", null);
        req.getSession().setAttribute("allCourses", list);
        req.getSession().setAttribute("myCourses",getMyCourses(req));
        req.getSession().setAttribute("p1","active");
        req.getSession().setAttribute("p2","");
        String url = (String) req.getSession().getAttribute("url");
        req.getRequestDispatcher(url).forward(req, resp);
    }

    private void myCourses(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("myCourses",getMyCourses(req));
        req.getSession().setAttribute("p1","");
        req.getSession().setAttribute("p2","active");
        String url = (String) req.getSession().getAttribute("url");
        req.getRequestDispatcher(url).forward(req, resp);
    }

    private void findCourses(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<CourseBean> list = new ArrayList<>();
        String keyWord = req.getParameter("keyWord");
        if (keyWord == null)
            keyWord = (String) req.getSession().getAttribute("keyWord");
        for (HashMap<String, String> m : new DB().query("*", "course", "course_name like '%" + keyWord + "%'"))
            list.add(new CourseBean(m));
        req.getSession().setAttribute("courseClass", "findCourses");
        req.getSession().setAttribute("findCourses", list);
        req.getSession().setAttribute("p1","active");
        req.getSession().setAttribute("p2","");
        req.getSession().setAttribute("keyWord", keyWord);
        String url = (String) req.getSession().getAttribute("url");
        req.getRequestDispatcher(url).forward(req, resp);
    }

    private void setCourse(HttpServletRequest req, HashMap<String, String> m) {
        m.put("course_name", req.getParameter("course_name"));
        m.put("teacher_name", req.getParameter("teacher_name"));
        m.put("classroom", req.getParameter("classroom"));
        m.put("course_time", req.getParameter("course_time"));
        m.put("credits", req.getParameter("credits"));
    }

    private List<CourseBean> getMyCourses(HttpServletRequest req) {
        List<CourseBean> list = new ArrayList<>();
        UserBean u = (UserBean) req.getSession().getAttribute("user");
        String id = u.getUser().get("id");
        for (HashMap<String, String> m : new DB().query("*", "course", "course_id in (select course_id from student_course where student_id='" + id + "')"))
            list.add(new CourseBean(m));
        return list;
    }
}
